﻿// -----------------------------------------------------------------------
// <copyright file="BinaryWriterAsync.cs">
// Copyright (c) 2013 Andrey Veselov. All rights reserved.
// License:  Microsoft Public License (MS-PL)
// Contacts: http://andrey.moveax.com  andrey@moveax.com
// </copyright>
// -----------------------------------------------------------------------

namespace PortableImagingLibrary.AsyncSupport
{
    using System;
    using System.Diagnostics.Contracts;
    using System.IO;
    using System.Text;
    using System.Threading.Tasks;

    internal class BinaryWriterAsync : IDisposable
    {
        private Stream _target;

        public BinaryWriterAsync(Stream target)
        {
            Contract.Requires(target != null);
            Contract.Requires(target.CanWrite);

            this._target = target;
        }

        public async Task WriteBytesAsync(byte[] source)
        {
            Contract.Requires(source != null);
            Contract.Requires(source.Length > 0);

            await this._target.WriteAsync(source, 0, source.Length)
                .ConfigureAwait(false);
        }

        public async Task WriteIntAsync(int source)
        {
            var buffer = BitConverter.GetBytes(source);
            Array.Reverse(buffer);

            await this._target.WriteAsync(buffer, 0, buffer.Length)
                .ConfigureAwait(false);
        }

        public async Task WriteUintAsync(uint source)
        {
            var buffer = BitConverter.GetBytes(source);
            Array.Reverse(buffer);

            await this._target.WriteAsync(buffer, 0, buffer.Length)
                .ConfigureAwait(false);
        }

        public async Task WriteStringAsync(string source)
        {
            Contract.Requires(!string.IsNullOrEmpty(source));

            var buffer = Encoding.UTF8.GetBytes(source);

            await this._target.WriteAsync(buffer, 0, buffer.Length)
                .ConfigureAwait(false);
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (this._target == null)
                return;

            this._target.Dispose();
            this._target = null;
        }

        #endregion IDisposable Members
    }
}
